<template>
	<view>
		<view @touchmove.prevent.stop>
			<uni-popup ref="auth" :custom="true" :mask-click="false">
				<view class="uni-tip">
					<view class="uni-tip-title">您还未登录</view>
					<view class="uni-tip-content">请先登录之后再进行操作</view>
					<view class="uni-tip-icon">
						<!-- <image :src="$util.img('/upload/uniapp/member/login.png')" mode="widthFix"></image> -->
						<button
							style="width: 120rpx;height: 120rpx;border-radius: 50%;padding: 0;background: rgba(0,0,0,0);margin-bottom: 20rpx;"
							class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image v-if="avatarUrl == ''"
								src="https://liaojianlian.axa2.com/upload/default/default_img/head.png"
								style="width: 120rpx;height: 120rpx;border-radius: 50%;" mode=""></image>
							<image style="width: 120rpx;height: 120rpx;border-radius: 50%;" class="avatar"
								:src="avatarUrl"></image>
						</button>
						<input type="nickname" v-model="nickname" @blur="changeInput" class="weui-input"
							placeholder="请输入昵称" />
					</view>
					<view class="uni-tip-group-button">
						<button type="default" class="uni-tip-button color-title close" @click="close">暂不登录</button>
						<!-- #ifdef MP-WEIXIN || MP-QQ || MP-BAIDU -->
						<button @click="login" class="uni-tip-button">立即登录</button>
						<!-- #endif  -->
						<!-- #ifdef MP-ALIPAY -->
						<button type="primary" open-type="getAuthorize" scope="userInfo" @getAuthorize="login"
							class="uni-tip-button color-base-bg">立即登录
						</button>
						<!-- #endif  -->
						<!-- #ifdef H5 -->
						<button type="primary" class="uni-tip-button color-base-bg" @click="login">立即登录</button>
						<!-- #endif  -->
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	const app = getApp().globalData;
	import uniPopup from '../uni-popup/uni-popup.vue';
	import auth from '../../common/js/auth.js'
	export default {
		mixins: [auth],
		name: 'ns-login',
		components: {
			uniPopup,
		},
		data() {
			return {
				url: '',
				registerConfig: {},
				avatarUrl: '',
				nickname: '',
				avatar_url: '',
				gender: '',
			};
		},
		created() {
			// this.getRegisterConfig();
		},
		mounted() {

			// #ifdef H5
			if (this.$util.isWeiXin()) {
				const getUrlCode = function() {
					var url = location.search;
					var theRequest = new Object();
					if (url.indexOf('?') != -1) {
						var str = url.substr(1);
						var strs = str.split('&');
						for (var i = 0; i < strs.length; i++) {
							theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
						}
					}
					return theRequest;
				};
				var urlParams = getUrlCode();
				if (urlParams.source_member) uni.setStorageSync('source_member', urlParams.source_member);
				if (urlParams.code != undefined) {
					this.$api.sendRequest({
						url: '/wechat/api/wechat/authcodetoopenid',
						data: {
							code: urlParams.code
						},
						success: res => {
							if (res.code >= 0) {
								let data = {};
								if (res.data.openid) data.wx_openid = res.data.openid;
								if (res.data.unionid) data.wx_unionid = res.data.unionid;
								if (res.data.userinfo) Object.assign(data, res.data.userinfo);
								this.authLogin(data);
							}
						}
					});
				}
			}
			// #endif
		},
		methods: {
			changeInput(e) {
				console.log(e, 'changeInput')
				this.nickname = e.detail.value
			},
			onChooseAvatar(e) {
				console.log(e, '111111111')
				let _this = this
				// const { avatarUrl } = e.detail 
				// this.setData({
				//   avatarUrl,
				// })
				_this.avatarUrl = e.detail.avatarUrl
				console.log(_this.avatarUrl, '_this.avatarUrl')

				uni.uploadFile({
					url: app.post_url + 'admin/api.Upload/file',
					filePath: _this.avatarUrl,
					name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
					header: {
						// "Authorization": uni.getStorageSync('token')
					},
					success: (res) => {
						let infoObj = JSON.parse(res.data)
						console.log(infoObj, '成功')
						_this.avatar_url = infoObj.data.url
						console.log(_this.avatar_url, '_this.avatar_url')
					},
					fail: (err) => {
						console.log(err, '失败')
					}
				})

			},
			/**
			 * 获取注册配置
			 */
			getRegisterConfig() {
				this.$api.sendRequest({
					url: '/api/register/config',
					success: res => {
						if (res.code >= 0) {
							this.registerConfig = res.data.value;
						}
					}
				});
			},
			open(url) {
				if (url) this.url = url;
				// #ifndef H5
				console.log('登陆')
				this.$refs.auth.open();
				// #endif

				// #ifdef H5
				if (this.$util.isWeiXin()) {
					let authData = uni.getStorageSync('authInfo');
					if (authData && authData.wx_openid && !uni.getStorageSync('loginLock')) {
						this.authLogin(authData);
					} else {
						this.$api.sendRequest({
							url: '/wechat/api/wechat/authcode',
							data: {
								redirect_url: location.href
							},
							success: res => {
								if (res.code >= 0) {
									location.href = res.data;
								} else {
									this.$util.showToast({
										title: '公众号配置错误'
									});
								}
							}
						});
					}
				} else {
					this.$refs.auth.open();
				}
				// #endif
			},
			close() {
				this.$refs.auth.close();
			},
			login(e) {
				let that = this;
				if (!uni.getStorageSync('loginLock')) {
					console.log('login')
					// #ifdef MP
					uni.getUserProfile({
						desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
						lang: 'zh_CN',
						success: (res) => {
							that.gender = res.userInfo.gender
							if (res.errMsg == 'getUserProfile:ok') {
								uni.login({
									provider: 'weixin',
									timeout: 3000,
									success: result => {
										if (result.code) {
											uni.request({
												url: app.post_url +
													'wechat/api.Login/query',
												//仅为示例，并非真实的接口地址
												data: {
													code: result.code,
												},
												method: 'post',

												success(res) {

													that.getuser(res.data.data.openid);

													// getApp().openid = res.data.openid;
												}

											});

										}
									},
									fail: () => {
										uni.showToast({
											title: '请求失败',
											icon: 'none'
										})
									}
								})

								// that.getCode(data => {
								// 	// debugger
								// 	if (data) {
								// 		// console.log('data',that.nickname)
								// 		console.log('data',res.userInfo.nickName)
								// 		let UserData = {
								// 			avatarUrl: res.userInfo.avatarUrl,
								// 			nickName: res.userInfo.nickName,
								// 			weapp_openid: data.weapp_openid,
								// 			source_member: data.source_member,
								// 			app_type: 'weapp',
								// 		};
								// 		that.authLogin(UserData);
								// 		// let UserData = {
								// 		// 	avatarUrl: that.avatar_url,
								// 		// 	nickName: that.nickname,
								// 		// 	weapp_openid: data.weapp_openid,
								// 		// 	source_member: data.source_member,
								// 		// 	app_type: 'weapp',
								// 		// };
								// 		// if(that.avatar_url != '' && that.nickname != ''){
								// 		// 	that.authLogin(UserData);
								// 		// }else {
								// 		// 	uni.showToast({
								// 		// 		title:'请获取头像和昵称',
								// 		// 		icon: 'none'
								// 		// 	})
								// 		// }

								// 	} else {
								// 		that.$refs.auth.close();
								// 		that.toLogin();
								// 	}
								// });
							}
						}
					})
					// #endif

					// #ifndef MP
					this.$refs.auth.close();
					this.toLogin();
					// #endif
				} else {
					this.$refs.auth.close();
					this.toLogin();
				}
			},
			//获取用户信息
			getuser: function(openid) {
				console.log(openid, 'openid1123123123')
				var _this = this;
				let data = {
					nickname: _this.nickname,
					headimg: _this.avatar_url,
					openid1: openid,
					base_sex: _this.gender

				}
				console.log(data, 'data')
				uni.request({
					url: app.post_url + 'wechat/api.Login/userLogin',
					//仅为示例，并非真实的接口地址
					data: data,
					method: 'post',

					success(res) {

						// _this.getorder(res.data.data.user_id);

						if (res.data.code == 1) {
							if (app.user_login == 0) {
								// app.user_info = res.data.data;
								// app.user_login = 1;
								uni.setStorageSync('userInfo', res.data.data)
								uni.setStorageSync('userId', res.data.data.id)
								uni.setStorageSync('login_check', 1)
								_this.$refs.auth.close();
								_this.$emit('loginSuccess')
								// uni.reLaunch({
								//     url: '/pages/mine/index'
								// })
							}

							// _this.setData({
							//   user: app.user_info,
							//   login_check: 1
							// });
						}else {
							uni.showToast({
								title:res.data.info,
								icon: 'none'
							})
						}
					}

				});
			},
			/**
			 * 跳转去登录页
			 */
			toLogin() {
				if (this.url) this.$util.redirectTo('/pages/login/login/login', {
					back: encodeURIComponent(this.url)
				});
				else this.$util.redirectTo('/pages/login/login/login');
			},
			/**
			 * 授权登录
			 */
			authLogin(data) {
				console.log(data, 'authLogin')
				uni.showLoading({
					title: '登录中'
				});
				uni.setStorage({
					key: 'authInfo',
					data: data
				});
				if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member');

				this.$api.sendRequest({
					url: '/api/login/auth',
					data,
					success: res => {
						this.$refs.auth.close();
						if (res.code >= 0) {
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									uni.removeStorageSync('loginLock');
									uni.removeStorageSync('unbound');
									uni.removeStorageSync('authInfo');
									this.$store.dispatch('getCartNumber');
									this.$store.commit('setToken', res.data.token);

									if (res.data.is_register && this.$refs.registerReward
										.getReward()) {
										this.$refs.registerReward.open();
									}
								}
							});
							setTimeout(() => {
								uni.hideLoading();
							}, 1000);
						} else if (this.registerConfig.third_party == 1 && this.registerConfig.bind_mobile ==
							1) {
							uni.hideLoading();
							this.$refs.bindMobile.open();
						} else if (this.registerConfig.third_party == 0) {
							uni.hideLoading();
							this.toLogin();
						} else {
							uni.hideLoading();
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						this.$refs.auth.close();
						this.$util.showToast({
							title: '登录失败'
						});
					}
				});
			}
		}
	};
</script>

<style lang="scss">
	.uni-tip {
		width: 580rpx;
		background: #fff;
		box-sizing: border-box;
		border-radius: 10rpx;
		overflow: hidden;
		height: initial;
	}

	.uni-tip-title {
		text-align: center;
		font-weight: bold;
		font-size: 32rpx;
		color: #303133;
		;
		padding-top: 50rpx;
	}

	.uni-tip-content {
		padding: 0 30rpx;
		color: #606266;
		font-size: 28rpx;
		text-align: center;
	}

	.uni-tip-icon {
		width: 100%;
		text-align: center;
		margin-top: 50rpx;
	}

	.uni-tip-icon image {
		width: 300rpx;
	}

	.uni-tip-group-button {
		margin-top: 30rpx;
		line-height: 120rpx;
		display: flex;
		padding: 0 50rpx 50rpx 50rpx;
		justify-content: space-between;
	}

	.uni-tip-button {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border: none;
		border-radius: 80rpx;
		padding: 0 !important;
		margin: 0 !important;
		background: #20A685;
		color: #ffffff;
		font-size: 28rpx;
	}

	.uni-tip-group-button .close {
		border: 1px solid #eee;
	}

	.uni-tip-button:after {
		border: none;
	}
</style>